package com.leo.netty.chart;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author du
 */
public class ChartClient {

    private String host;
    private int port;

    public ChartClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //inbound
                            ch.pipeline().addLast("decoder", new StringDecoder());
                            //outbound
                            ch.pipeline().addLast("encoder", new StringEncoder());
                            // 自定义inbound
                            ch.pipeline().addLast(new ClientHandler());
                            System.out.println("Channel 初始化完毕.");
                        }
                    });

            ChannelFuture future1 = b.connect(host, port).sync().addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    System.out.println("监听端口8888成功");
                } else {
                    System.out.println("监听端口8888失败");
                }
            });

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                future1.channel().writeAndFlush(msg + "\r\n");
            }

            // 阻塞监听关闭事件
            future1.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new ChartClient("127.0.0.1", 8888).run();
    }

    static class ClientHandler extends SimpleChannelInboundHandler<String> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            // 接收服务端消息并打印
            System.out.println(msg.trim());
        }
    }
}
